<template>
  <div class="login_container">
    <div class="main">
      <div id="head">
        <span>登录</span>
        <el-popover
          placement="top-start"
          class="popover"
          width="200"
          trigger="hover"
        >
          <span>
            <strong> 默认账号：</strong>it+学号 <br />
            <strong>默认密码：</strong>学号</span
          >
          <span slot="reference"><i class="el-icon-info"></i></span>
        </el-popover>
      </div>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 账户登录 -->
        <div v-show="!show" class="infos">
          <el-form-item label="" prop="username">
            <el-input
              class="inputbox"
              placeholder="请输入用户名"
              prefix-icon="el-icon-user-solid"
              type="text"
              v-model="ruleForm.username"
              @input="inputLimit"
              @keyup.enter.native="submitForm('ruleForm')"
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="password">
            <el-input
              class="inputbox"
              type="password"
              prefix-icon="el-icon-lock"
              placeholder="请输入密码（默认密码：学号）"
              :show-password="true"
              v-model="ruleForm.password"
              @keyup.enter.native="submitForm('ruleForm')"
            ></el-input>
          </el-form-item>
          <el-form-item label="" prop="captcha" class="captcha_input">
            <el-input
              class="inputbox"
              type="text"
              prefix-icon="el-icon-key"
              placeholder="请输入图片验证码"
              v-model="ruleForm.captcha"
              @keyup.enter.native="submitForm('ruleForm')"
            ></el-input>
            <div id="imgArea">
              <img
                id="captcha"
                :src="captchaUrl"
                alt=""
                @click="refreshCaptcha()"
              />
            </div>
          </el-form-item>
        </div>
        <div class="bottom">
          <el-button
            size="normal"
            type="primary"
            @click="submitForm('ruleForm')"
            >登录</el-button
          >
          <el-button size="normal" type="success" plain @click="handleGuest"
            >游客入口</el-button
          >
        </div>
      </el-form>
      <div class="getpassword">
        <span @click="toForgetPassword" class="text">忘记密码？</span>
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    //判断函数
    var validateAccount = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else if (value.length < 6) {
        callback(new Error("密码长度不得小于6位"));
      } else {
        callback();
      }
    };
    return {
      show: false,
      captchaUrl: "",
      sec: "",
      //发回的验证码
      code: "",
      showbtn: true,
      tipMessage: "",
      ruleForm: {
        password: "",
        username: "",
        panduan: true,
      },
      rules: {
        password: [{ validator: validatePass, trigger: "blur" }],
        username: [{ validator: validateAccount, trigger: "blur" }],
        captcha: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.refreshCaptcha();
  },
  methods: {
    async refreshCaptcha() {
      const res = await this.$axios.get(
        `${this.HOST}/captcha.jpg` + "?random=" + Math.random(),
        { responseType: "arraybuffer" }
      );
      //将从后台获取的图片流进行转换
      this.captchaUrl =
        "data:image/png;base64," +
        btoa(
          new Uint8Array(res.data).reduce(
            (data, byte) => data + String.fromCharCode(byte),
            ""
          )
        );
    },
    handleGuest() {
      window.sessionStorage.setItem("isGuest", "1");
      this.$router.push("/welcome");
    },
    //判断是否标准账号格式
    inputLimit(val) {
      // 正则匹配非中英文及数字的字符
      // let reg = /[^\u4e00-\u9fa5a-zA-Z0-9]/;
      // 正则匹配非英文及数字的字符
      let reg = /[^a-zA-Z0-9]/;
      // 查找是否有非中英文及数字的字符
      // 没有则返回-1，有则返回对应位置
      let n = val.search(reg);
      // 由于每次触发，通常只有最后一个字符是有可能异常的
      // 所以这里是直接截取异常字符前面的部分
      if (n !== -1) {
        this.ruleForm.username = val.slice(0, n);
      }
      // console.log(n);
    },
    //提交设置
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        // console.log(valid);
        if (valid) {
          const params = {
            username: this.ruleForm.username,
            password: this.ruleForm.password,
            captcha: this.ruleForm.captcha,
            rememberMe: 1,
          };
          const formData = new FormData();
          Object.keys(params).forEach((key) => {
            formData.append(key, params[key]);
          });
          // console.log("form", formData);
          try {
            const res = await this.$axios.post(`${this.HOST}/login`, formData);
            // console.log("res=", res);
            if (res.data.meta.code == 200) {
              this.$notify({
                title: "登录成功！",
                message:
                  res.data.data.user.realName + ",你好！\n欢迎登录IT培优",
                type: "success",
                offset: 66,
              });
              window.sessionStorage.setItem("token", res.headers.token);
              window.sessionStorage.setItem(
                "user",
                JSON.stringify(res.data.data.user)
              );
              window.sessionStorage.setItem("isGuest", "0");
              window.sessionStorage.setItem(
                "groupId",
                JSON.stringify(this.getArrGroup(res.data.data.user.groupId))
              );

              this.$router.push("/home");
            } else {
              this.refreshCaptcha();
              this.ruleForm.captcha = "";
            }
          } catch (err) {
            // console.log("err", err);
            this.$message({
              message: "用户名或密码错误",
              type: "error",
            });
            this.ruleForm.password = "";
            this.ruleForm.captcha = "";
            this.refreshCaptcha();
          }
        } else {
          return false;
        }
      });
    },
    //重置设置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getArrGroup(e) {
      // console.log("e", e);
      let arr = new Array();
      // 一级
      arr.push(10000);
      // console.log("arr", arr);
      //二级
      if (e % 10000 == 0) return arr;
      // console.log((e / 1000) * 1000);
      arr.push(parseInt(e / 1000) * 1000);
      // console.log("arr", arr);
      // 三级
      if (e % 1000 == 0) return arr;
      arr.push(parseInt(e / 10) * 10);
      // console.log("arr", arr);
      // 四级
      if (e % 10 == 0) return arr;
      arr.push(e);
      // 返回
      // console.log("arr", arr);
      return arr;
    },
    /**
     * 点击忘记密码
     */
    toForgetPassword() {
      this.$emit('to-forget');
    },
  },
};
</script>
<style lang='less' scope>
.login_container {
  // border: 1px black solid ;
  // height: 100%;
  // width: 100%;
  top: 35%;

  .main {
    width: 450px;
    // display: inline-block;
    padding-bottom: 10px;
    margin: auto;
    background-color: rgba(255, 255, 255, 0.4) !important;
    // background-color: rgba(255, 255, 255, 1) !important;
    // position: absolute;
    // left: 50%;
    // top: 50%;
    box-shadow: 0px 15px 25px rgba(0, 0, 0, 0.5);
    /*边框阴影  水平阴影0 垂直阴影15px 模糊25px 颜色黑色透明度0.5*/
    // border-radius: 10px;

    .infos {
      // padding-right: 80px;
      width: 350px;

      /deep/.inputbox {
        border-radius: 10px;
        background-color: rgba(255, 255, 255, 0.377);

        &::placeholder {
          color: rgb(114, 112, 112);
        }
      }

      /deep/ .el-input__inner {
        background: blue !important;
      }
    }

    #head {
      font-weight: bold;
      text-align: center;
      width: 100%;
      height: 70px;
      line-height: 60px;
      color: rgb(85, 85, 85);
      font-size: 22px;

      .popover {
        z-index: 10;
        margin-left: 5px;
      }
    }

    .bottom {
      width: 200px;
      margin: 20px auto;
      // border: 1px solid black;
      display: flex;
      justify-content: center;

      // .forget {
      //   font-size: 14px;
      //   color: #dcddd8;

      //   .word {
      //     cursor: pointer;
      //     margin-right: 40px;
      //     color: #dcddd8;
      //   }
      //   .word:hover {
      //     // position: relative;
      //     // bottom: 0px;
      //     // padding: 0px;
      //     margin-right: 40px;
      //     cursor: pointer;
      //     color: rgb(46, 158, 255);
      //     text-decoration: underline;
      //   }
      // }
    }
  }
}
#imgArea {
  width: 100%;
  // padding-left: 250px;
  // position: absolute;
  // top: 0;
  // right: 0;
  #captcha {
    border-radius: 5px;
    position: absolute;
    top: 0;
    right: 0;
    width: 90px;
    height: 40px;
  }
}
.getpassword {
  width: 100%;
  text-align: end;
  font-size: 16px;

  .text {
    display: inline-block;
  }

  .text:hover {
    font-weight: bold;
    cursor: pointer;
  }
}
</style>
